package gov.nhso.prov.acc.servlets;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import gov.nhso.prov.acc.core.ConfigBundle;
import gov.nhso.prov.acc.ftp.BAAC2NHSO;
import gov.nhso.prov.acc.ftp.NHSO2BAAC;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

/**
 * Servlet implementation class BatchFTP
 */
public class BatchFTP extends HttpServlet {
       
    /**
	 * 
	 */
	private static final long serialVersionUID = 960750368048425905L;

	/**
     * @see HttpServlet#HttpServlet()
     */
    public BatchFTP() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		try {
			if (ConfigBundle.getValue("BATCH_FTP").equals("Y")) {
				// Grab the Scheduler instance from the Factory
				SchedulerFactory sf = new StdSchedulerFactory();
				Scheduler sched = sf.getScheduler();

				// define the job and tie it to our HelloJob class
				JobDetail job = newJob(NHSO2BAAC.class).withIdentity("NHSO2BAAC", "batch").build();
				
				CronTrigger trigger = newTrigger().withIdentity("trigger1", "batch").withSchedule(cronSchedule(ConfigBundle.getValue("NHSO2BAAC"))).build();
				
				//CronTrigger trigger = newTrigger().withIdentity("trigger1", "batch").withSchedule(cronSchedule("0 0/15 * * * ?")).build();

				sched.scheduleJob(job, trigger);

				job = newJob(BAAC2NHSO.class).withIdentity("BAAC2NHSO", "batch").build();

				trigger = newTrigger().withIdentity("trigger2", "batch").withSchedule(cronSchedule(ConfigBundle.getValue("BAAC2NHSO"))).build();
				
				//trigger = newTrigger().withIdentity("trigger2", "batch").withSchedule(cronSchedule("0 0/10 * * * ?")).build();

				sched.scheduleJob(job, trigger);

				sched.start();
				System.out.println("------- Started Scheduler -----------------");
				//System.out.println("------- Waiting five minutes... ------------");
				//try {
			            // wait five minutes to show jobs
			            //Thread.sleep(10 * 1000L);
			            // executing...
			    //} catch (Exception e) {}
			 
				//sched.shutdown(true);
				//System.out.println("------- Shutdown Complete -----------------");
				//SchedulerMetaData metaData = sched.getMetaData();
				//System.out.println("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
			}

        } catch (SchedulerException se) {
            se.printStackTrace();
        } 
	}

}
